package iterator;

import java.util.ArrayList;
import java.util.List;

// 聚合接口
interface Aggregate<T> {
    Iterator<T> iterator();
}

// 具体聚合
class MyList<T> implements Aggregate<T> {
    private final List<T> items = new ArrayList<>();

    public void add(T item) {
        items.add(item);
    }

    @Override
    public Iterator<T> iterator() {
        return new ListIterator<>(items);
    }
}

// 迭代器接口
interface Iterator<T> {
    boolean hasNext();

    T next();
}

// 具体迭代器
class ListIterator<T> implements Iterator<T> {
    private final List<T> list;
    private int index = 0;

    public ListIterator(List<T> list) {
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        return index < list.size();
    }

    @Override
    public T next() {
        return list.get(index++);
    }
}

public class IteratorPatternDemo {
    public static void main(String[] args) {
        MyList<String> names = new MyList<>();
        names.add("Alex");
        names.add("Tom");
        names.add("Jerry");

        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}